package com.example.interceptmybatis.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.example.interceptmybatis.config.Result;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.ap.shaded.freemarker.template.utility.StringUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @ClassName FileController
 * @Description TODO
 * @Author 郭敖
 * @Date 2024年10月09日 13:18
 * @Version 1.0
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    private final String filePath = "D:\\workspace\\file\\image";

    @GetMapping("/getJson")
    public String getJson(HttpServletResponse response) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "test");
        jsonObject.put("age", 18);
        jsonObject.put("sex", "男");
//        response.setHeader("Content-Disposition", "attachment;filename=test.json");
//        response.setContentType("application/octet-stream");
//        response.getOutputStream().write(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
        return jsonObject.toJSONString();
    }

//    @PostMapping("/upload")
//    public Result<FileVO> upload(MultipartFile file) throws IOException {
//        String originalFilename = file.getOriginalFilename();
//        log.info("文件名:{}", originalFilename);
//        String type = Objects.requireNonNull(file.getOriginalFilename()).split("\\.")[1];
//        String format = DateUtil.format(LocalDateTime.now(), "yyyy.MM.dd");
//        String fileName = format + "/" + UUID.randomUUID().toString(true) + "." +type;
//        String path = filePath + "/" + fileName;
//        FileUtil.writeFromStream(file.getInputStream(), path);
//        FileVO fileVO = new FileVO();
//        fileVO.setFileName(fileName.replace('/','-'));
//        fileVO.setFilePath(path);
//        return Result.Success(fileVO);
//    }

    @GetMapping("/images")
    public void images(@RequestParam("url") String url, HttpServletResponse response) throws IOException {
        url = url.replace("-", "/");
        String path = filePath + "/" + url;
        File file = new File(path);
        log.info("文件路径:{}", path);
        response.setContentType("image/jpeg");
        IoUtil.copy(FileUtil.getInputStream(file), response.getOutputStream());
    }

}
